<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$bus.$emit('getPage',pageNo-1)">上一页</button>
    <button v-if="startNumAndEnd.start > 1" @click="$bus.$emit('getPage',1)">1</button>
    <button v-if="startNumAndEnd.start > 2">···</button>

    <button v-if="page >= startNumAndEnd.start"
            v-for="(page) in startNumAndEnd.end"
            @click="$bus.$emit('getPage',page)"
    :class="{active:page === pageNo}">{{page}}
    </button>

    <button v-if="startNumAndEnd.end !== totalPage">···</button>
    <button v-if="startNumAndEnd.end < totalPage"  @click="$bus.$emit('getPage',total)">{{ totalPage }}</button>
    <button :disabled="pageNo === total" @click="$bus.$emit('getPage',pageNo+1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>

</template>

<script>
export default {
  name: "Pagination",
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    //计算获取回来的数据的总页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize)  //向上取整计算出总页数
    },
    //计算连续页的 start 和 end
    startNumAndEnd() {
      let {continues,pageNo,totalPage} = this;   //结构赋值
      let start = 0 //连续页的开始页
      let end = 0;  //连续页的结束页

      if(continues > totalPage){
        // 处理连续页大于总页数
        start = 1;
        end = totalPage;
      }else {
        // 连续页小于总页数（正常情况）
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        if(start < 1){
          // 处理start为负数的情况
          start = 1;
          end = continues;
        }
        if(end > totalPage){
          // 处理end大于总页码数的情况
          end = totalPage;
          start = totalPage - continues + 1;
        }
      }
      return {start,end};
    }

  },
  methods: {

  },
  mounted() {
    
  }
}
</script>

<style scoped lang="less">
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}

</style>